﻿layui.define(['laypage', 'layer','table', 'form', 'pagesize'], function (exports) {
    var $ = layui.jquery,
        layer = layui.layer,
        table = layui.table,
        form = layui.form;
    // 分类值
    var cid;
    // 关键词/字
    var keyword;

    var tableIns = table.render({
        elem: "#databox",
        method: "get",
        page:true, // 开启分页
        url: "getinfo", // 数据接口
        // height: "full-20",
        cellMinWidth: 80,
        cols: [[ // 表头
            // {field:"id", title: "ID", width:50, sort:true, fixed: 'left'},
            {field:"created_at", title: "创建时间", width:200, sort:true},
            {field:"category_name", title: "分类名称", width:150},
            {field:"title", title: "标题", width:150},
            {field:"author", title: "作者", width:150},
            {field:"description", title: "描述"},
            {field:"is_show", title: "是否显示", width:150,align:'center',
                templet: function (d) {
                    var status = '';
                    if(d.status === 1) { status = 'checked'; }
                    return '<form class="layui-form" action=""> <div class="layui-form-item" style="margin:0;"> <input type="checkbox" name="status" title="显示" lay-filter="show" value="'+d.id+'" '+status+'></div> </form>';
                }
            },
            {field:"is_original", title: "是否顶置", width:150,align:'center',
                templet: function (d) {
                    var is_top = '';
                    if(d.is_top == 1) { is_top = 'checked'; }
                    return '<form class="layui-form" action=""> <div class="layui-form-item" style="margin:0;"> <input type="checkbox" name="is_top" title="置顶" lay-filter="top" value="'+d.id+'" '+is_top+'> </div> </form>';
                }
            },
            {field:"deleted_at", title: '状态', width:100, align: 'center',
                templet: function (d) {
                    var textStatus = "";
                    var displayStatus = 'blockStatus';
                    if(d.deleted_at) {
                        textStatus += '<button class="layui-btn layui-btn-xs layui-btn-radius layui-btn-disabled blockStatus">已删除</button>';
                        displayStatus = 'noneStatus';
                    } else {
                        textStatus += '<button class="layui-btn layui-btn-xs layui-btn-radius layui-btn-disabled noneStatus">已删除</button>';
                    }
                    textStatus += '<button class="layui-btn layui-btn-xs layui-btn-radius '+displayStatus+'">使用中</button>';
                    return textStatus;
                }
            },
            {field:"", title: "操作", width: 200,align:'center',
                templet:function (d) {
                    var html = '<button title="编辑" class="layui-btn layui-btn-sm layui-btn-normal" onclick="layui.articleList.editData('+d.id+')">' +
                        '<i class="layui-icon">&#xe642;</i>' +
                        '</button>';
                    if(d.deleted_at) {
                        html += '<button title="永久删除" class="layui-btn layui-btn-sm layui-btn-danger" onclick="layui.articleList.forceDelete(this,'+d.id+')">' +
                            '<i class="layui-icon">&#x1006;</i>' +
                            '</button>';
                        html += '<button title="还原删除" class="layui-btn layui-btn-sm" onclick="layui.articleList.restoreData(this,'+d.id+')">' +
                            '<i class="layui-icon">&#xe669;</i>' +
                            '</button>';
                    } else {
                        html += '<button title="删除" class="layui-btn layui-btn-sm layui-btn-warm" onclick="layui.articleList.softDelete(this,'+d.id+')">' +
                            '<i class="layui-icon">&#xe640;</i>' +
                            '</button>';
                    }
                    return html;
                }
            }
        ]],
        done: function (res) {
            // console.log(res);
        }
    });

    // 监听分类选项SelectBox
    form.on('select(category)',function (data) {
        cid = data.value;
        tableIns.reload({
            where: {
                cid:cid,
                keyword:keyword
            },
            page: {
                curr: 1 // 重新从第1页开始
            }
        });
    });

    // 监听关键字/词 keyword
    $("#keyword").change(function() {
        keyword = $(this).val();
        tableIns.reload({
            where: {
                cid:cid,
                keyword:keyword
            },
            page: {
                curr: 1 // 重新从第1页开始
            }
        });
    });

    //监听置顶CheckBox
    form.on('checkbox(top)', function (data) {
        var id = data.value;
        var field = 'is_top';
        var value = data.elem.checked;
        value = (value === true) ? 1 : 2;
        saveData(id,field,value);
    });

    //监听显示CheckBox
    form.on('checkbox(show)', function (data) {
        var id = data.value;
        var field = 'status';
        var value = data.elem.checked;
        value = (value === true) ? 1 : 2;
        saveData(id,field,value);
    });

    $(document).ready(function () {
        categoryinit();
    });

    /**
     * 加载分类列表
     */
    function categoryinit() {
        $.ajax({
            url: "/admin/article/category/getlist",
            type: "get",
            dataType: "json",
            success:function (msg) {
                if(msg.code > 0) {
                    layer.msg(msg.message || '操作失败,返回原来状态');
                } else {
                    var str_select = '';
                    $.each(msg.data,function (index,value) {
                        str_select += '<option value="'+value.id+'">'+value.name+'</option>';
                    });
                    $(str_select).appendTo($("#categorybox"));
                    form.render();
                }
            },
            error:function (msg) {
                layer.msg("服务器繁忙，请稍后再试");
            }
        });
    }


    /**
     * 更改状态
     * @param id    数据ID
     * @param field 字段名称
     * @param value 数据值
     */
    function saveData(id,field,value) {
        setTimeout(function () {
            $.ajax({
                type: 'post',
                url: 'save',
                data: {id:id,field:field,value:value},
                dataType: "json",
                success:function(res) {
                    if(res.code > 0) {
                        layer.msg(res.message || '操作失败,返回原来状态');
                        return false;
                    }else{
                        layer.msg('操作成功');
                        return true;
                    }
                },
                error:function (msg) {
                    layer.msg("服务器繁忙，请稍后再试");
                }
            });
            form.render();  //重新渲染
        }, 300);
    }

    //输出接口，主要是两个函数，一个删除一个编辑
    var articleList = {
        softDelete: function (index,id) {
            var index = index;
            layer.confirm('确定删除？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                $.ajax({
                    type: 'post',
                    url: "destroy",
                    data: {id:id},
                    dataType:"json",
                    success:function(res) {
                        if(res.code !== 0) {
                            layer.msg(res.message || '操作失败');
                            return false;
                        } else {
                            var statusbtn1 = $(index).parents('td').prev().find('.blockStatus');
                            var statusbtn2 = $(index).parents('td').prev().find('.noneStatus');
                            statusbtn1.addClass('noneStatus').removeClass('blockStatus');
                            statusbtn2.addClass('blockStatus').removeClass('noneStatus');
                            var html = '<button title="永久删除" class="layui-btn layui-btn-sm layui-btn-danger" onclick="layui.articleList.forceDelete(this,'+id+')"><i class="layui-icon">&#x1006;</i></button><button title="还原删除" class="layui-btn layui-btn-sm" onclick="layui.articleList.restoreData(this,'+id+')"><i class="layui-icon">&#xe669;</i></button>';
                            $(index).parent().append(html);
                            $(index).remove();
                            layer.msg('删除成功', {icon: 6});
                        }
                    },
                    error:function (msg) {
                        layer.msg("服务器繁忙，请稍后再试");
                    }
                });
            }, function () {

            });
        },
        editData: function (id) {
            window.location.href = "/admin/article/edit/"+id;
        },
        restoreData: function (index,id) {
            $.ajax({
                type: "post",
                url: 'restore',
                dataType: "json",
                data: {id: id},
                success:function (resp) {
                    if(resp.code === 0) {
                        var statusbtn1 = $(index).parents('td').prev().find('.blockStatus');
                        var statusbtn2 = $(index).parents('td').prev().find('.noneStatus');
                        statusbtn1.addClass('noneStatus').removeClass('blockStatus');
                        statusbtn2.addClass('blockStatus').removeClass('noneStatus');
                        var actHtml = '<button title="编辑" class="layui-btn layui-btn-sm layui-btn-normal" onclick="layui.articleList.editDataPage('+id+')"><i class="layui-icon">&#xe642;</i></button><button title="删除" class="layui-btn layui-btn-sm layui-btn-warm" onclick="layui.articleList.softDelete(this,'+id+')"><i class="layui-icon">&#xe640;</i></button>';
                        $(index).parent().html(actHtml);
                        layer.msg('恢复成功', {icon: 6});
                    } else {
                        layer.msg(resp.message || '操作失败', {icon: 5});
                    }
                },
                error:function (resp) {
                    layer.msg('服务繁忙');
                }
            });
        },
        forceDelete: function (index,id) {
            layer.confirm('此操作无法恢复，是否确认删除？', {
                btn: ['确认','取消']
            }, function () {
                $.ajax({
                    type: "post",
                    url: "delete",
                    dataType: "json",
                    data: {id:id},
                    success:function (resp) {
                        if(resp.code === 0) {
                            $(index).parents('tr').remove();
                            layer.msg('删除成功',{icon:6});
                        } else {
                            layer.msg(resp.message || '操作失败',{icon:5});
                        }
                    },
                    error:function (resp) {
                        layer.msg('服务繁忙');
                    }
                });
            });
        }
    };
    exports('articleList', articleList);
});
